# 文件名：BMI.py
import tkinter as tk
from tkinter import messagebox


# 计算BMI值的函数
def calculate_bmi(weight, height):
    try:
        # 计算体重除以身高的平方
        bmi = weight / (height ** 2)
        # 返回格式化的BMI值，保留两位小数
        return f"BMI: {bmi:.2f}"
    except Exception as e:
        # 如果计算过程中出现异常，返回错误信息
        return "Error in calculation"


# 根据BMI值返回身体状况类别和描述的函数
def get_bmi_category(bmi):
    if bmi < 18.5:
        return "Underweight", "体重过轻"  # BMI小于18.5，体重过轻
    elif bmi < 24.9:
        return "Normal", "正常范围"  # BMI在18.5到24.9之间，正常范围
    elif bmi < 29.9:
        return "Overweight", "超重"  # BMI在24.9到29.9之间，超重
    else:
        return "Obese", "肥胖"  # BMI大于或等于29.9，肥胖


# 创建BMI计算窗口的函数
def switch_to_bmi(window):
    # 隐藏主窗口
    window.withdraw()
    # 创建新的顶级窗口作为BMI计算器
    bmi_window = tk.Toplevel()
    # 设置窗口标题
    bmi_window.title("BMI计算")
    # 设置窗口大小
    bmi_window.geometry("400x350")
    # 创建并放置体重输入的标签和输入框
    tk.Label(bmi_window, text="请输入体重（kg），例如80（kg）:").pack()
    weight_entry = tk.Entry(bmi_window)
    weight_entry.pack()
    # 创建并放置身高输入的标签和输入框
    tk.Label(bmi_window, text="请输入身高（m），例如1.8（m）:").pack()
    height_entry = tk.Entry(bmi_window)
    height_entry.pack()
    # 创建一个标签用于显示BMI结果和身体状况
    result_label = tk.Label(bmi_window, text="", wraplength=400)
    result_label.pack()

    # 定义计算并显示BMI的函数
    def calculate_and_display_bmi():
        try:
            # 从输入框获取体重和身高
            weight = float(weight_entry.get())
            height = float(height_entry.get())
            # 计算BMI
            bmi = calculate_bmi(weight, height)
            # 获取BMI分类和描述
            category, description = get_bmi_category(float(bmi.split(':')[1].strip()))
            # 显示BMI结果和身体状况描述
            result_label.config(text=f"{bmi}\n{category}: {description}")
        except ValueError:
            # 如果输入不是有效的数字，显示错误信息
            messagebox.showerror("错误", "请输入合适的数字")

    # 创建计算BMI的按钮
    calculate_button = tk.Button(bmi_window, text="计算BMI", command=calculate_and_display_bmi)
    calculate_button.pack()

    # 创建返回按钮，点击后关闭BMI窗口并恢复主窗口
    return_button = tk.Button(bmi_window, text="返回", command=lambda: [bmi_window.destroy(), window.deiconify()])
    return_button.pack()
